import axios from 'axios'
import { useUserStore } from "@/stores/userStore"
import { ElMessage } from 'element-plus'
import router from "@/router/index"
// 创建axios实例
const instance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 5000
})

// axios请求拦截器
instance.interceptors.request.use(config => {
  // 1. 从pinia获取token数据
  const userStore = useUserStore()
  // 2. 按照后端的要求拼接token数据

  const token = userStore.userInfo && userStore.userInfo.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }

  return config
}, e => Promise.reject(e))

// axios响应式拦截器
instance.interceptors.response.use(res => res.data, e => {
  const userStore = useUserStore()
  //统一错误提示

  ElNotification({
    title: '错误',
    message: e.response.data.message,
    type: 'error',
  })
  //401，token失效
  if (e.response.status == 401) {
    userStore.clearUserInfo()
    router.replace("/login")
  }

  return Promise.reject(e)
})


export default instance